package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.cst.SysConst;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.PageReq;
import com.itheima.entity.PageRes;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealGroup;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealGroupService;
import com.itheima.service.SetmealService;
import com.itheima.utils.FileUtils;
import com.itheima.utils.RedisUtil;
import com.itheima.vo.CheckGroupVO;
import com.itheima.vo.SetmealPieVO;
import com.itheima.vo.SetmealVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Resource
    private SetmealGroupService setmealGroupService;

    @Resource
    private CheckGroupService checkGroupService;

    @Resource
    private CheckItemService checkItemService;

//    @Resource
//    RedisTemplate<String,Object> redisTemplate;

    @Transactional
    public boolean saveSetmeal(SetmealDto setmealDto) {
        //1.保存套餐信息
        this.saveOrUpdate(setmealDto.getSetmeal());
        //将正确的img path移除出集合
        RedisUtil.removeSetMember(SysConst.FILE_ALL_SET_KEY,setmealDto.getSetmeal().getImg());
//        redisTemplate.opsForSet().remove("file:allset",setmealDto.getSetmeal().getImg());
        //2.清空套餐与检查组关系
        setmealGroupService.deleteBySetmealId(setmealDto.getSetmeal().getId());
        //3.维护新的套餐与检查组关系
        if(setmealDto.getGroupIds() != null){
            List<SetmealGroup> list = new ArrayList<>();
            for(long groupId : setmealDto.getGroupIds()){
                SetmealGroup setmealGroup = new SetmealGroup();
                setmealGroup.setGroupId(groupId);
                setmealGroup.setSetmealId(setmealDto.getSetmeal().getId());
                list.add(setmealGroup);
            }
            setmealGroupService.saveBatch(list);
        }
        return true;
    }

    @Override
    public boolean deleteById(Long id) {
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setIs_delete(1);
        return this.updateById(setmeal);
    }

    @Override
    public PageRes<Setmeal> findByPage(PageReq req) {
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0);
        String queryString = req.getQueryString();
        if(queryString != null && "".equals(queryString.trim()) == false){
            queryWrapper.and(wrapper -> {
                wrapper.like("name",queryString).or()
                        .like("code",queryString).or()
                        .like("help_code",queryString);
            });
        }
        IPage<Setmeal> result = this.page(new Page<>(req.getCurrentPage(),req.getPageSize()),queryWrapper);
        return new PageRes<>(result.getTotal(),result.getRecords());
    }

    @Override
    public boolean clearOssObject() {
//        Set<Object> set = redisTemplate.opsForSet().members("file:allset");
        Set<Object> set = RedisUtil.getMembersOfSet(SysConst.FILE_ALL_SET_KEY);
        if(set != null && set.isEmpty() == false){
            for(Object obj : set){
                String path = (String)obj;
//                if(redisTemplate.opsForValue().get("file:" + path) == null){
                if(RedisUtil.existsKey(SysConst.FILE_BASE_KEY + path) == false){
                    FileUtils.delete(path);
//                    redisTemplate.opsForSet().remove("file:allset",path);
                    RedisUtil.removeSetMember(SysConst.FILE_ALL_SET_KEY,path);
                }
            }
        }
        return true;
    }

    @Override
    public List<Setmeal> findAll() {
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0);
        return this.list(queryWrapper);
    }

    @Override
    public SetmealVO getInfo(Long id) {
        return this.baseMapper.getInfo(id);
    }

    @Override
    public SetmealVO getDetail(Long id) {
        //1.查询套餐基本信息
        SetmealVO setmealVO = getInfo(id);
        //2.套餐vo里面设置检查组集合
        //select g.* from setmeal_group_t r
        //left join check_group_t g on g.id = r.group_id
        //where setmeal_id = 2
        setmealVO.setCheckGroups(checkGroupService.selectBySetmealId(id));
        //1,2,3,4,5
        if(setmealVO.getCheckGroups() != null){
            for(CheckGroupVO checkGroupVO : setmealVO.getCheckGroups()){
                //3.检查组里面查询检查项集合
                //select i.* from check_group_item_t r
                //left join check_item_t i on r.item_id = i.id
                //where group_id = 28
                checkGroupVO.setCheckItems(checkItemService.selectByGroupId(checkGroupVO.getId()));
            }
        }
        return setmealVO;
    }

    @Override
    public SetmealPieVO getSetmealPieData() {
        SetmealPieVO setmealPieVO = new SetmealPieVO();
        setmealPieVO.setData(this.baseMapper.selectSetmealPieData());
        if(setmealPieVO.getData() != null){
            setmealPieVO.setLegendLabels(new ArrayList<>());
            setmealPieVO.getData().forEach(item -> {
                setmealPieVO.getLegendLabels().add((String)item.get("name"));
            });
        }
        return setmealPieVO;
    }
}
